<template>
	<div class="container">
		<div>
			<el-button type="primary" icon="el-icon-plus" @click="editVisible = true" v-permission
				class="toolBarButton">
				新增
			</el-button>
			<v-nodeDBToolBar :fullPath="postData.opera" :tableColumns="tableColumns" @changeLie="getChangeLie"
				@getSearchIPArr="getToolBarSearchIPArr" @getSearchIP="getToolBarSearchIP"
				@selectIsEnabled="getToolBarSelectIsEnabled" @selectDBType="getToolBarSelectDBType"
				@selectSERVICESNAME="getToolBarSelectSERVICESNAME">
			</v-nodeDBToolBar>
			
		</div>
		<!--  -->
		<el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
			class="tableData" :data="tableDataFn" highlight-current-row @current-change="handleCurrentChange" border
			stripe style="width: 100%">
			<el-table-column type="index" :index="1" width="50" label="序号">
			</el-table-column>

			<template v-for="item in tableColumns">
				<el-table-column :prop="item.prop" :label="item.label" :sortable="item.sortable" :width="item.width"
					align="center" v-if="item.isShow" :key="item.prop">
					<template v-slot="scope">
						<template v-if="item.format == 'ISENABLED'">
							<div>
								<template v-if="scope.row[item.prop] == 'Y'">
									<el-tag type="success">监控中</el-tag>
								</template>
								<template v-else-if="scope.row[item.prop] == 'N'">
									<el-tag type="danger">待开启</el-tag>
								</template>
								<template v-else>
									<el-tooltip class="item" effect="dark" :content="scope.row[item.prop]"
										placement="right">
										<el-tag type="danger" effect="dark">异常值</el-tag>
									</el-tooltip>
								</template>
							</div>
						</template>
						<template v-else-if="item.format == 'password'">
							<div>
								<!-- <div v-if="scope.row.showPswd = false">******</div>
								<div v-if="scope.row.showPswd = true">
									{{scope.row.password}}
								</div> -->
								{{ scope.row["showPswd"] ? scope.row[item.prop] : "******" }}
								<!-- <i class="el-icon-view pswdBtn" @click="showPswdFn(scope.$index, scope.row)"></i> -->
							</div>
						</template>
						<template v-else-if="item.format == 'handleRow'">
							<div>
								<el-button type="warning" @click="editNode(scope.row)" v-permission>编辑</el-button>
								<template v-if="scope.row['ISENABLED'] == 'Y'">
									<el-button type="danger" @click="editNodeMonitor(scope.row, 'N')" v-permission
										:loading="scope.row.editNodeMonitorBtnDisabled">
										关闭监控
									</el-button>
								</template>
								<template v-else>
									<el-button type="success" @click="editNodeMonitor(scope.row, 'Y')" v-permission
										:loading="scope.row.editNodeMonitorBtnDisabled">
										开启监控
									</el-button>
								</template>
							</div>
						</template>
						<template v-else-if="item.format == 'alertLevelConfig'">
							<div>
								{{ alertLevelConfigOptionText(scope.row[item.prop]) }}
							</div>
						</template>
						<template v-else>
							<div>
								{{ scope.row[item.prop] }}
							</div>
						</template>
					</template>
				</el-table-column>
			</template>
		</el-table>
		<v-pagination :dataTotal="dataTotal" :curPage="postData.curPage" :pageSize="postData.pageSize"
			@getCurPage="getPaginationCurPage" @getPageSize="getPaginationPageSize">
		</v-pagination>

		<!-- 新建、编辑对话框 -->
		<el-dialog :visible.sync="editVisible" width="24%" @close="resetForm('nodeForm')">
			<el-form :model="nodeForm" :rules="nodeFormRules" ref="nodeForm" label-width="120px">
				<el-form-item label="IP" prop="IP">
					<el-input v-model="nodeForm.IP"></el-input>
				</el-form-item>
				<el-form-item label="系统名称" prop="SYSTEMNAME">
					<el-input v-model="nodeForm.SYSTEMNAME"></el-input>
				</el-form-item>
				<el-form-item label="业务系统" prop="BID">
					<el-select v-model="nodeForm.BID" filterable>
						<el-option v-for="item in servicesNameOption" :key="item.BID" :label="item.NAME"
							:value="item.BID">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所属监控组" prop="ALERT_LEVELCONFIG">
					<el-select v-model="nodeForm.ALERT_LEVELCONFIG" filterable>
						<el-option v-for="item in alertLevelConfigOptionFn" :key="item.ID" :label="item.TITLE"
							:value="item.ID">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="数据库类型">
					<el-radio-group v-model="nodeForm.DBTYPE" @change="CreatType">
						<el-radio key="Oracle" label="Oracle">Oracle</el-radio>
						<el-radio key="SQLServer" label="SQLServer">SQLServer</el-radio>
						<el-radio key="Mysql" label="Mysql">Mysql</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="数据库名" prop="DB_SERVERNAME" v-if="this.createOpera !== 'CreatemysqlMonitor'">
					<el-input v-model="nodeForm.DB_SERVERNAME"></el-input>
				</el-form-item>
				<el-form-item label="DB_SID" prop="DB_SID" v-if="this.createOpera !== 'CreatemysqlMonitor'">
					<el-input v-model="nodeForm.DB_SID"></el-input>
				</el-form-item>
				<el-form-item label="端口" prop="PORT">
					<el-input v-model="nodeForm.PORT" onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="请输入数字">
					</el-input>
				</el-form-item>
				<el-form-item label="监控状态" prop="ISENABLED">
					<el-radio-group v-model="nodeForm.ISENABLED"
						:fill="nodeForm.ISENABLED == 'Y' ? '#67C23A' : '#F56C6C'">
						<el-radio-button key="Y" label="Y">开启</el-radio-button>
						<el-radio-button key="N" label="N">关闭</el-radio-button>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="12c及以上版本?" prop="ISENABLED" v-if="nodeForm.DBTYPE === 'Oracle'">
					<el-radio-group v-model="nodeForm.VERSION" :fill="nodeForm.VERSION == 'Y' ? '#67C23A' : '#F56C6C'">
						<el-radio-button key="Y" label="Y">是</el-radio-button>
						<el-radio-button key="N" label="N">否</el-radio-button>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="告警日志">
					<el-input v-model="nodeForm.ALERTLOG"></el-input>
				</el-form-item>
				<el-form-item label="用户名" prop="DB_USER_S">
					<el-input v-model="nodeForm.DB_USER_S"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="DB_PWD_S">
					<el-input v-model="nodeForm.DB_PWD_S" show-password></el-input>
				</el-form-item>
			</el-form>
			
			<span slot="footer">
				<el-button @click="editVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitData('nodeForm')" :disabled="submitBtnDisabled">
					确 定
				</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		submitAdmin,
		TryLinkDataBase
	} from "../../../api/index.js";
	import vPagination from "../../common/Pagination.vue";
	import vNodeDBToolBar from "./NodeDBToolBar.vue";
	import tableColumns from "./NodeDBColumns.js";
	export default {
		components: {
			vPagination,
			vNodeDBToolBar,
		},
		data() {
			return {
				postData: {
					opera: "GetDBMonitor",
					curPage: 1,
					pageSize: 20,
					sort: {
						sortColumn: "",
						sortOrders: "",
					},
					filtersType: "fuzzyquery",
					filters: {},
				},
				tableData: [],
				dataTotal: 0,
				tableColumns: tableColumns,
				SearchIPArr: [],
				searchJson: {},
				searchIP: "",
				editVisible: false,
				submitBtnDisabled: false,
				editNodeMonitorBtnDisabled: false,
				nodeForm: {
					// CID: '',    编辑用到
					IP: "",
					BID: "0",
					ALERT_LEVELCONFIG: "0",
					DBTYPE: "Oracle",
					DB_SERVERNAME: "",
					DB_SID: "",
					PORT: 1521,
					ISENABLED: "Y",
					ALERTLOG: "",
					DB_USER_S: "",
					DB_PWD_S: "",
					SYSTEMNAME: "",
					VERSION: "N",
				},
				nodeFormRules: {
					IP: [{
							required: true,
							message: "请输入IP",
							trigger: "blur"
						},
						{
							pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,
							message: "请输入正确的IP",
						},
					],
					SYSTEMNAME: [{
						required: true,
						message: "请输入系统名称",
						trigger: "blur"
					}, ],
					DB_SERVERNAME: [{
						required: true,
						message: "请输入数据库名",
						trigger: "blur"
					}, ],
					DB_SID: [{
						required: true,
						message: "请输入DB_SID",
						trigger: "blur"
					}],
					PORT: [{
						required: true,
						message: "请输入端口",
						trigger: "blur"
					}],
					DB_USER_S: [{
						required: true,
						message: "请输入用户名",
						trigger: "blur"
					}, ],
					DB_PWD_S: [{
						required: true,
						message: "请输入密码",
						trigger: "blur"
					}],
				},
				createOpera: "CreateDBMonitor",
				modifyOpera: "ModifyDBMonitor",
				loading: true,
				loadingOptions: {
					target: ".el-table",
					lock: true,
					fullscreen: false,
					text: "Loading",
					spinner: "el-icon-loading",
					background: "rgba(0, 0, 0, 0.7)",
				},
				alertLevelConfigOption: [],
				servicesNameOption: [],
			};
		},
		created() {
			// this.CreatType();
			this.getTableData();
			this.getAlertGroupIndex();
			this.getServicesNameOption();
		},
		computed: {
			tableDataFn() {
				return this.tableData.filter((item) => {
					item["showPswd"] = false;
					// item["editNodeMonitorBtnDisabled"] = false
					return item;
				});
				console.log(123,this.tableData)
			},
			alertLevelConfigOptionFn() {
				return this.alertLevelConfigOption.filter((item) => {
					if (item.GROUP_TYPE == "ALL" || item.GROUP_TYPE == "Database") {
						return item;
					}
				});
			},
		},
		methods: {
			CreatType(value) {
				console.log(value)
				if(value == 'Oracle'){
					this.nodeForm.PORT = 1521
				}else if(value == 'SQLServer'){
					this.nodeForm.PORT = 1433
				}else if(value == 'Mysql'){
					this.nodeForm.PORT = 3306
				}
				switch (value) {
					case "Oracle":
						value = "CreateDBMonitor";
						break;
					case "SQLServer":
						// value = 'SQLServer' //2021 0630 提交不了修改
						value = "CreateDBMonitor";
						break;
					case "Mysql":
						// value = 'CreatemysqlMonitor'  //2021 0708 提交不了修改
						value = "CreateDBMonitor";
						// this.postData.opera = 'GetmysqlMonitor'
						// this.modifyOpera = 'ModifymysqlMonitor'
						break;
					default:
						break;
				}
				this.createOpera = value;
				// console.log(this.createOpera)
			},
			async getTableData() {
				// await getUserData("userBase", "infoBase", 0).then((res) => {
				//   this.userAuthority = res.userAuthority;
				// });
				// let _loadingInstance = this.$loading(this.loadingOptions);
				this.loading = true;

				submitAdmin({
						postData: JSON.stringify(this.postData),
					})
					.then((res) => {
						// console.log(123,this.postData)
						this.dataTotal = res.dataTotal;
						this.tableData = res.data;
						res.data.forEach((item) => {
							item.editNodeMonitorBtnDisabled = false;
						});
						console.log(res.data);

						// _loadingInstance.close();
					})
					.catch((e) => {
						this.$message.error("请求失败");
					})
					.finally(() => {
						this.loading = false;
					});
			},
			getAlertGroupIndex() {
				let _postData = {
					opera: "GetAlertGroupIndex",
					curPage: 1,
					pageSize: 10000,
					sort: {
						sortColumn: "",
						sortOrders: "",
					},
					filtersType: "exactquery", // 精确查询
					filters: {},
				};

				submitAdmin({
					postData: JSON.stringify(_postData),
				}).then((res) => {
					this.alertLevelConfigOption = res.data;
				});
			},
			getServicesNameOption() {
				let _postData = {
					opera: "GetServicesName",
					curPage: 1,
					pageSize: 10000,
					sort: {
						sortColumn: "",
						sortOrders: "",
					},
					filtersType: "exactquery", // 精确查询
					filters: {},
				};

				submitAdmin({
					postData: JSON.stringify(_postData),
				}).then((res) => {
					this.servicesNameOption = res.data;
				});
			},
			alertLevelConfigOptionText(id) {
				let _text = "";
				this.alertLevelConfigOption.forEach((element) => {
					if (element.ID == id) {
						_text = element.TITLE;
					}
				});

				return _text;
			},
			getPaginationCurPage(val) {
				this.postData.curPage = val;

				this.getTableData();
			},
			getPaginationPageSize(val) {
				// 分页大小改变之后，重置当前页码为 1
				this.postData.curPage = 1;
				this.postData.pageSize = val;

				this.getTableData();
			},
			getToolBarSearchIPArr(arr) {
				// 获取搜索IP关键字
				this.SearchIPArr = arr;

				this.postData.curPage = 1;
				if (this.SearchIPArr.length > 0) {
					this.postData.filters = {
						ip: this.SearchIPArr,
					};
				} else {
					this.postData.filters = {};
				}

				this.getTableData();
			},
			getToolBarSearchIP(str) {
				// 获取搜索IP关键字
				this.SearchIP = str;
				this.postData.curPage = 1;
				this.postData.filters = {
					ip: this.SearchIP,
				};
				this.getTableData();
			},
			getToolBarSelectIsEnabled(val) {
				this.postData.filters["ISENABLED"] = val;
				this.getTableData();
			},
			getToolBarSelectDBType(val) {
				this.postData.filters["DBTYPE"] = val;
				this.getTableData();
			},
			getToolBarSelectSERVICESNAME(val) {
				this.postData.filters["SERVICESNAME"] = val;
				this.getTableData();
			},
			getChangeLie(val) {
				// 遍历表格列
				this.tableColumns.map((item, index) => {
					// 列的显示隐藏状态改变
					item.isShow = val.includes(item.label);
				});
			},
			handleCurrentChange(currentRow, oldCurrentRow) {
				// if (currentRow != null) {
				//   currentRow["isEdit"] = true;
				// }
				// if (oldCurrentRow != null) {
				//   oldCurrentRow["isEdit"] = false;
				// }
			},
			resetForm(formName) {
				let _data = new Object();
				Object.assign(_data, this.$options.data()[formName]);
				this.$data[formName] = _data;

				// 移除表单校验结果
				this.$refs[formName] && this.$refs[formName].clearValidate();
			},
			submitData(formName) {
				let _this = this;
				this.$refs[formName].validate((valid) => {
					if (valid) {
						// if (this.createOpera == 'CreatemysqlMonitor') {
						//     let _mysqlObject = {
						//         // CID: '',    编辑用到
						//         IP: this.nodeForm.IP,
						//         BID: this.nodeForm.BID,
						//         ALERT_LEVELCONFIG: "0",
						//         DBTYPE: "Mysql",
						//         DB_SERVERNAME: '',
						//         DB_SID: '',
						//         PORT: 1521,
						//         ISENABLED: "Y",
						//         ALERTLOG: this.nodeForm.ALERTLOG,
						//         Mysql_USER_S: this.nodeForm.DB_USER_S,
						//         Mysql_PWD_S: this.nodeForm.DB_PWD_S,
						//         SYSTEMNAME: ""
						//     };

						//     console.log(this.nodeForm);

						// };
						this.nodeForm = this.nodeForm;
						// 禁用按钮，避免重复提交
						this.submitBtnDisabled = true;
						// 处理需要提交数据
						let _postData = {
							opera: "",
							data: [this.nodeForm],
						};

						if (this.nodeForm.hasOwnProperty("CID")) {
							_postData.opera = this.modifyOpera;
						} else {
							_postData.opera = this.createOpera;
							// console.log("yitijiao " + this.createOpera);
						}
						const sucb = () => {
							submitAdmin({
								postData: JSON.stringify(_postData),
							}).then((res) => {
								if (res == "创建成功" || res == "修改成功") {
									this.$message.success({
										message: "操作成功",
										duration: 1000,
									});
									this.editVisible = false;
									this.getTableData();
								} else {
									this.$message.error({
										message: "操作失败",
										duration: 3000,
									});
								}
								// 启用按钮
								this.submitBtnDisabled = false;
							});
						};
						const errcb = (_) => {
							this.$message.error({
								message: `系统与${_postData.data[0].IP}连接失败,原因：${_}`,
								duration: 8000,
								onClose: async () => {
									_this.submitBtnDisabled = false;
									_this.getTableData();
								},
							});
						};

						if (_postData.data[0].ISENABLED == "Y") {
							let tryData = {
								dbtype: _postData.data[0].DBTYPE,
								ip: _postData.data[0].IP,
								port: _postData.data[0].PORT,
								sid: _postData.data[0].DB_SID,
								dbservername: _postData.data[0].DB_SERVERNAME,
								user: _postData.data[0].DB_USER_S,
								password: _postData.data[0].DB_PWD_S,
								version: _postData.data[0].VERSION,
							};
							this.tryToConnect(tryData, sucb, errcb);
						} else {
							sucb();
						}

						// 提交数据
					} else {
						return false;
					}
				});
			},
			editNode(rowData) {
				for (const key in this.nodeForm) {
					if (rowData.hasOwnProperty(key)) {
						this.nodeForm[key] = rowData[key];
					}
				}
				this.nodeForm.CID = rowData.CID;
				this.editVisible = true;
			},
			editNodeMonitor(rowData, flag) {
				// 禁用按钮
				const ThisRowData = rowData;
				ThisRowData.editNodeMonitorBtnDisabled = true;

				// 数据处理
				let _postData = {
					opera: this.modifyOpera,
					data: [this.nodeForm],
				};
				for (const key in _postData.data[0]) {
					if (rowData.hasOwnProperty(key)) {
						_postData.data[0][key] = rowData[key];
					}
				}
				_postData.data[0].CID = rowData.CID;
				_postData.data[0].ISENABLED = flag;

				const _this = this;
				const errcb = (_) => {
					this.$message.error({
						message: `系统与${rowData.IP}连接失败,原因：${_}`,
						duration: 8000,
						onClose: async () => {
							ThisRowData.editNodeMonitorBtnDisabled = false;
							_this.getTableData();
						},
					});
				};
				const sucb = () => {
					submitAdmin({
						postData: JSON.stringify(_postData),
					}).then((res) => {
						if (res == "修改成功") {
							this.$message.success({
								message: "操作成功",
								duration: 1000,
								onClose: () => {
									ThisRowData.editNodeMonitorBtnDisabled = false;
								},
							});
							this.getTableData();
						} else {
							this.$message.error({
								message: "操作失败",
								duration: 1000,
								onClose: () => {
									ThisRowData.editNodeMonitorBtnDisabled = false;
								},
							});
						}
					});
				};

				if (flag == "Y") {
					let tryData = {
						dbtype: _postData.data[0].DBTYPE,
						ip: _postData.data[0].IP,
						port: _postData.data[0].PORT,
						sid: _postData.data[0].DB_SID,
						dbservername: _postData.data[0].DB_SERVERNAME,
						user: _postData.data[0].DB_USER_S,
						password: _postData.data[0].DB_PWD_S,
						version: _postData.data[0].VERSION,
					};
					this.tryToConnect(tryData, sucb, errcb);
				} else {
					sucb();
				}

				this.resetForm("nodeForm");
			},
			tryToConnect(postData, sucb, errcb) {
				TryLinkDataBase({
						...postData
					})
					.then((_) => {
						if (_ === 1) {
							sucb();
						} else {
							errcb(_);
						}
					})
					.catch((_) => {
						errcb(_);
					});
			},
			searchData() {
				this.postData.filters["IP"] = this.searchIP;
				this.getTableData();
			},
			showPswdFn(index, row) {
				console.log(index,row)
				row["showPswd"] = !row["showPswd"];
				// this.tableData.showPswd = !this.tableData.showPswd
				this.$set(this.tableDataFn, index, row);
			},
		},
		watch: {},
	};
</script>

<style scoped>
	.el-table .warning-row {
		background: oldlace;
	}

	.el-table .success-row {
		background: #f0f9eb;
	}

	.toolBarButton {
		float: left;
		padding-bottom: 10px;
		margin-right: 20px;
	}

	.pswdBtn {
		float: right;
		line-height: 23px;
		color: #67c23a;
		font-size: 18px;
	}

	.pswdBtn:hover {
		cursor: pointer;
	}
</style>
